/**
 *发送GET异步请求
 * @param {String} url
 * @param {String} params
 * @param {Object} headerFn
 * @param {string} [dataType='json']
 * @returns Promise
 */
function get(url, params, headerFn, dataType = 'json') {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        if (xhr.status === 200) {
          let res = xhr.responseText
          switch (dataType) {
            case 'json':
              res = JSON.parse(xhr.responseText)
              break;
            default:
              break;
          }
          resolve(res)
        } else {
          reject('芭比Q了', xhr.status)
        }
      }
    }
    let tempArr = []
    for (let k in params) {
      tempArr.push(`${k}=${params[k]}`)
    }
    xhr.open('get', `${url}?${tempArr.join('&')}`)
    for (let key in headerFn) {
      xhr.setRequestHeader(key, headerFn[key])
    }
    xhr.send(null)
  })
}


/**
 *发送POST异步请求
 * @param {String} url
 * @param {String} params
 * @param {Object} headerFn
 * @param {string} [dataType='json']
 * @returns Promise
 */
function post(url, params, headerFn, dataType = 'json') {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        if (xhr.status === 200) {
          let res = xhr.responseText
          switch (dataType) {
            case 'json':
              res = JSON.parse(xhr.responseText)
              break;
            default:
              break;
          }
          resolve(res)
        } else {
          reject('芭比Q了', xhr.status)
        }
      }
    }
    xhr.open('post', url)
    xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
    for (let key in headerFn) {
      xhr.setRequestHeader(key, headerFn[key])
    }
    var tempArr = []
    for (let k in params) {
      tempArr.push(`${k}=${params[k]}`)
    }
    xhr.send(tempArr.join('&'))
  })
}

